package org.springsource.authentication;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springsource.dao.AccountDao;
import org.springsource.domain.Account;

@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired 
	private AccountDao accountDao;
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Account account = accountDao.getAccount(username);
		if(account == null){
			 throw new UsernameNotFoundException("user not found");
		}
		return buildUserFromUserEntity(account);
	}
	private User buildUserFromUserEntity(Account account) {

	    String username = account.getUsername();
	    String password = account.getPassword();

	    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	    authorities.add(new SimpleGrantedAuthority("USER"));

	    User user = new User(username, password, true,
	      true, true, true, authorities);
	    return user;
	  }

}
